package commit

import (
	"context"
	"fmt"
	"github.com/Unixeno/islands/cmd/connection"
	"github.com/Unixeno/islands/cmd/container"
	"github.com/Unixeno/islands/cmd/utils"
	"github.com/Unixeno/islands/pb"
	"github.com/spf13/cobra"
)

func GetCommitCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "commit id imagename",
		Short: "commit a container to image repository",
		Long:  `commit a specific container to image repository`,
		Args:  cobra.MinimumNArgs(2),
		Run:   commitHandle,
	}
}

func commitHandle(cmd *cobra.Command, args []string) {
	id := args[0]
	name := args[1]

	id = container.CheckNameOrId(id)

	r, err := connection.Client.CommitContainer(context.Background(), &pb.CommitContainerReq{
		Id:                   id,
		Name:                 name,
	})

	if err != nil {
		fmt.Printf("Cannot commit the container for reason %v\n", err)
	} else {
		if !utils.PrintError(r.Err) {
			fmt.Println(r.Id)
		}
	}
}